/*
 *  JVending
 *  Copyright (C) 2004  Shane Isbell
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package org.jvending.provisioning.match;

import javax.provisioning.BundleDescriptor;
import javax.provisioning.MatchPolicy;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Matches a bundle descriptor from the <code>BundleDescriptorRepository</code> by keyword.
 *
 * @author Shane Isbell
 * @since 1.3.9a
 */

public final class KeywordSearch implements MatchPolicy {

    private static Logger logger = Logger.getLogger("Keyword Search");

    private String text;

    private Pattern pattern;

    public KeywordSearch(String text) {
        this.text = text;
        if (text != null) pattern = Pattern.compile(text);
    }

    public float doMatch(BundleDescriptor bundleDescriptor) {
        if (bundleDescriptor == null) return 0f;
        if (text == null || text.equals("")) return 1.0f;

        String keywords = bundleDescriptor.getCatalogProperty("Keywords");
        if (keywords == null) return 0f;

        String[] keywordTokens = keywords.split("[,]");
        int length = keywordTokens.length;

        int matches = 0;
        for (int i = 0; i < length; i++) {
            Matcher matcher = pattern.matcher(keywordTokens[i].trim());
            if (matcher.matches() == true) matches++;
        }
        float match = (float) matches / length;
        logger.finest("Keyword Match: Value = " + match + ", Keywords = " + keywords + ", Text = " + text);

        return match;
    }

}